<template>
  <div class="app-container">
    <div class="create-container">
      <el-form ref="form" :model="form" :rules="rules" inline-message="true" class="form-container">
        <el-form-item :label="$t('user')+$t('type')" label-width="120px">
          <el-input v-model="groupName" style="width: 250px;" disabled />
        </el-form-item>
        <el-form-item :label="$t('nickname')" label-width="120px" prop="name">
          <el-input v-model="form.name" autocomplete="off" style="width: 250px;" />
        </el-form-item>
        <el-form-item :label="$t('telephone')" label-width="120px" prop="telephone">
          <el-input v-model="form.telephone" autocomplete="off" style="width: 250px;" />
        </el-form-item>
        <el-form-item :label="$t('email')" label-width="120px" prop="email">
          <el-input v-model="form.email" autocomplete="off" style="width: 250px;" />
        </el-form-item>
        <el-form-item :label="$t('avatar')" label-width="120px">
          <!-- 显示当前选中的头像 -->
          <el-image :src="avatarList[form.avatar]" fit="cover" style="width: 100px; height: 100px;"></el-image>
          <!-- 使用 div 来展示头像列表 -->
          <div class="avatar-grid" v-if="avatarList.length > 0">
            <el-image
              v-for="(avatarUrl, index) in avatarList"
              :key="index"
              :src="avatarUrl"
              fit="cover"
              style="width: 50px; height: 50px;"
              @click="selectAvatar(index)"
            ></el-image>
          </div>
        </el-form-item>
      </el-form>
      
      <div class="dialog-footer">
        <!-- <el-button @click="cancel">{{ $t('cancel') }}</el-button> -->
        <el-link style="margin:10px 70px 0 0; float: right;" @click="openUpdatePasswordDialog"> 
            {{ $t('change') }}{{ $t('password') }} 
        </el-link>
        <el-button type="primary" @click="onEdit">
            {{ $t('confirm') }}
        </el-button>
        <!-- <el-button @click="resetPassword"> {{ $t('reset') }}{{ $t('password') }} </el-button> -->
        <!-- <el-button @click="openUpdatePasswordDialog"> {{ $t('change') }}{{ $t('password') }} </el-button> -->
      </div>
    </div>

    <!-- 更新密码浮窗 -->
    <el-dialog :title="$t('modify') + $t('password')" :visible.sync="resetDialogVisible" width="30%">
      <template slot="title">
        <span class="dialog-title">{{ $t('modify') }}{{ $t('password') }}</span>
      </template>
      <el-form :model="setPasswdForm" :rules="modifyPasswordRules" ref="resetPasswordForm" label-width="80px" class="dialog-form">
        <el-form-item :label="$t('Old_password')" prop="oldPwd">
          <el-input v-model="setPasswdForm.oldPwd" type="password" autocomplete="off" show-password />
        </el-form-item>
        <el-form-item :label="$t('New_password')" prop="pwd">
          <el-input v-model="setPasswdForm.pwd" type="password" autocomplete="off" show-password />
        </el-form-item>
        <el-form-item :label="$t('Confirm_password')" prop="confirmPassword">
          <el-input v-model="setPasswdForm.confirmPassword" type="password" autocomplete="off" show-password />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: right; margin-top: 0; padding-top: 0;">
        <el-button @click="resetDialogVisible = false; resetPasswordInput = ''; resetID = 0">{{ $t('cancel') }}</el-button>
        <el-button type="primary" @click="updatePassword">{{ $t('confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getDetail, updateUser, resetPassword, updatePassword} from '@/api/user.js'
import SearchPanel from '@/components/SearchPanel/index.vue'
import md5 from 'js-md5'

function newForm() {
  return {
    id: 0,
    name: '',
    telephone: '',
    email: '',
    groupId: 1,
    avatar: 0
  }
}

function checkPhone(rule, value, callback) {
  const reg = /^\d{11}$/
  if (!reg.test(value)) {
    callback(new Error(this.$t('user_phone_rule')))
  } else {
    callback()
  }
}

export default {
  components: {
    SearchPanel
  },
  data() {
    return {
      form: {
        id: 0,
        name: '',
        telephone: '',
        email: '',
        groupId: 1,
        avatar: -1
      },
      groupName: '',
      listLoading: true,
      resetPasswordInput: '',
      resetID: 0,
      resetDialogVisible: false,
      setPasswdForm: {
        oldPwd: '',
        pwd: '',
        confirmPassword: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入用户名称', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        telephone: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { min: 11, max: 11, message: this.$t('user_phone_rule'), trigger: 'blur' },
          { type: 'number', validator: checkPhone, message: '请填写正确手机号', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        groupId: [
          { required: true, message: '请选择用户组', trigger: 'blur' }
        ]
      },
      modifyPasswordRules: {
        oldPwd: [
          { required: true, message: '请输入旧密码', trigger: 'blur' }
        ],
        pwd: [
          { required: true, message: '请输入新密码', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value === this.setPasswdForm.pwd) {
                callback()
              } else {
                callback(new Error('两次输入密码不一致'))
              }
            },
            trigger: 'blur'
          }
        ]
      },
      avatarList: [
      require('@/assets/avatars/1.jpg'),
        require('@/assets/avatars/2.jpg'),
        require('@/assets/avatars/3.jpg'),
        require('@/assets/avatars/4.jpg'),
        require('@/assets/avatars/5.jpg'),
        require('@/assets/avatars/6.jpg'),
        require('@/assets/avatars/7.jpg'),
        require('@/assets/avatars/8.jpg'),
        require('@/assets/avatars/9.jpg'),
        require('@/assets/avatars/10.jpg'),
        require('@/assets/avatars/11.jpg'),
        require('@/assets/avatars/12.jpg'),
        require('@/assets/avatars/13.jpg'),
        require('@/assets/avatars/14.jpg'),
        require('@/assets/avatars/15.jpg'),
        require('@/assets/avatars/16.jpg'),
        require('@/assets/avatars/17.jpg'),
        require('@/assets/avatars/18.jpg'),
        require('@/assets/avatars/19.jpg'),
        require('@/assets/avatars/20.jpg'),
      ],
    }
  },
  created() {
    this.form = newForm()
    this.getData()
  },
  methods: {
    getData() {
      this.listLoading = true
      // 加载用户数据回显
      getDetail().then(response => {
        this.form = {
          id: response.data.id,
          name : response.data.name,
          telephone : response.data.telephone,
          email : response.data.email,
          groupId : response.data.group_id,
          avatar : response.data.avatar
        }
        this.groupName = this.getGroupNameById(this.form.groupId)
        this.listLoading = false
      })
    },
    getGroupNameById(id) {
      if (id === 1) {
        return '管理员'
      } else if (id === 2) {
        return '开发者'
      }
    },
    onEdit() {
      this.$refs['form'].validate((valid) => {
        if (!valid) {
          this.$message({
            type: 'warning',
            message: '请检查输入内容是否符合要求'
          })
          return
        } else {
          updateUser(this.form).then(() => {
            this.$message({
              type: 'success',
              message: '编辑成功'
            })
            if (this.$store.getters.isSelf(this.form.id)) {
              console.log(this.$store.getters.avatar)
              this.$store.dispatch('user/getInfo')
            }
            this.getData(1)
            location.reload();
          })
        }
      })
    },
    resetPassword() {
      this.$confirm('此操作将重置该用户密码, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false
      }).then(() => {
        resetPassword(this.form.id).then(() => {
          this.$message({
            type: 'success',
            message: '密码重置成功'
          })
        }).catch(error => {
          console.error(error)
          this.$message({
            type: 'error',
            message: '密码重置失败'
          })
        })
      })
    },

    openUpdatePasswordDialog(){
      this.resetDialogVisible = true
    },

    // 修改密码成功后清空表单
    updatePassword() {
      this.$refs['resetPasswordForm'].validate((valid) => {
        if (!valid) {
          this.$message({
            type: 'warning',
            message: '请检查输入内容是否符合要求'
          });
          return;
        }
        // 更新密码逻辑
        let formdata = {
          id: this.form.id,
          old_password: md5(this.setPasswdForm.oldPwd),
          new_password: md5(this.setPasswdForm.pwd)
        };

        updatePassword(formdata).then(() => {
          this.$message({
            type: 'success',
            message: '密码更新成功'
          });
          // 清空表单
          this.setPasswdForm = {
            oldPwd: '',
            pwd: '',
            confirmPassword: ''
          };
          this.resetDialogVisible = false;
          if (this.$store.getters.isSelf(this.form.id)) {
            this.$store.dispatch('user/getInfo');
          }
        }).catch(error => {
          console.error(error);
          this.$message({
            type: 'error',
            message: '密码更新失败，请检查输入'
          });
        });
      });
    },

    selectAvatar(index) {
      this.form.avatar = index;
    },
  }
}
</script>

<style scoped>
.app-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.create-container {
  width: 100%;
  max-width: 1000px;
  padding: 20px;
  border-left: 1px solid #DCDFE6;
  border-radius: 4px !important;
  background-color: #fff;
}

.dialog-footer {
  text-align: left;
  margin-left: 120px;
  margin-top: 20px;
}
.avatar-grid {
  display: flex;
  flex-wrap: wrap;
  margin-top: 10px;
  gap: 30px; /* 间距 */
}
</style>